package com.cloud.wms.http.observer;


import android.text.TextUtils;

import com.cloud.core.http.HttpCode;
import com.cloud.core.http.error.AppException;
import com.cloud.core.http.error.ERROR;
import com.cloud.core.utils.JsonUtils;
import com.cloud.wms.http.ErrorEntity;

import io.reactivex.functions.Function;
import retrofit2.HttpException;
import retrofit2.Response;

/**
 * @Author:Chen
 * @Date: 2021-01-19 15:48
 * @Description:
 */
public class ResponseWrapper<T> implements Function<Response<T>, T> {

    @Override
    public T apply(Response<T> response) throws Exception {
        if (response.code() == HttpCode.OK) {
            return response.body();
        }
        if (response.code() == HttpCode.OK_VOID) {
            return (T) new Object();
        }
        if (response.code() == HttpCode.OK_UNAUTHORIZED && !TextUtils.isEmpty(response.headers().get("Token-Expired"))) {
            throw new AppException(ERROR.TOKEN_INVALID, "授权失败，请登录重试");
        }
        String error = response.errorBody().string();
        ErrorEntity errorEntity = JsonUtils.json2Bean(error, ErrorEntity.class);
        if (errorEntity != null) {
            throw new AppException(errorEntity.getErrorMsg());
        } else {
            throw new HttpException(response);
        }
    }
}
